package com.xzt.meeting.service;

import com.xzt.meeting.dao.ArticleDao;
import com.xzt.meeting.entity.Article;
import com.xzt.meeting.entity.PageEntity;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author xzt
 * @Date 2022/5/8 18:11
 * @Version 1.0
 * @Introduce
 */
public class ArticleService {

    private ArticleDao articleDao = new ArticleDao();

    public PageEntity<Article> findPage(Integer currpage, String title) {
        PageEntity<Article> pageEntity = new PageEntity<>();

        pageEntity.setCurrPage(currpage);

        Integer pageSize = pageEntity.getPageSize();

        Integer startIndex = (currpage-1) * pageSize;

        List<Article> data = articleDao.findPage(title,startIndex,pageSize);

        Integer totalCount = articleDao.countBytitle(title);

        Integer totalPage = totalCount % pageSize == 0 ? totalCount/pageSize : (totalCount/pageSize) + 1;

        pageEntity.setTotalPage(totalPage);
        pageEntity.setTotalCount(totalCount);
        pageEntity.setData(data);
        return pageEntity;
    }

    public void addArt(Article article) {
        article.setBrowseCount(0L);      //默认浏览量为0
        article.setPublishDate(new Date());        //当前时间发布

        articleDao.save(article);
    }

    public void updateBrowserCount(Long id) {
        articleDao.updateBrowserCount(id);
    }

    public Article findById(Long id) {
        return articleDao.findById(id);
    }

    public Integer countFavoriteByArticleId(Long id) {
        return articleDao.countFavoriteByArticleId(id);
    }

    public Boolean isFavorite(Long uid, Long aid) {
        Integer count =articleDao.countByUserIdAndArticleId(uid,aid);
        return count==0? false:true;
    }

    public List<Map<String, Object>> findUserFavorite(Long uid, Long aid) {
        return articleDao.findUserFavorite(uid,aid);
    }

    public void unFavorite(Long uid, Long aid) {
        articleDao.unFavorite(uid,aid);
    }

    public void favorite(Long uid, Long aid) {
        articleDao.favorite(uid,aid);
    }

    public PageEntity<Article> favoritePage(Integer currpage, String title, Long id) {
        PageEntity<Article> pageEntity = new PageEntity<>();

        pageEntity.setCurrPage(currpage);

        Integer pageSize = pageEntity.getPageSize();

        Integer startIndex = (currpage-1) * pageSize;

        List<Article> data = articleDao.favoritePage(id,title,startIndex,pageSize);

        Integer totalCount = articleDao.countFavoritePageBytitle(id,title);

        Integer totalPage = totalCount % pageSize == 0 ? totalCount/pageSize : (totalCount/pageSize) + 1;

        pageEntity.setTotalPage(totalPage);
        pageEntity.setTotalCount(totalCount);
        pageEntity.setData(data);
        return pageEntity;
    }
}
